package cn.aopmin;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

public class KillPortDemo {

    public static void main(String[] args) {
        System.out.println("=============【欢迎使用端口释放工具】=============");
        System.out.println("请输入要释放的端口:");
        // 拼接cmd命令
        String port = new Scanner(System.in).next();
        String command = "cmd /c netstat -ano | findstr :" + port;
        try {
            // 执行命令,拿到端口占用信息
            Process process = Runtime.getRuntime().exec(command);
            // 读取命令执行结果
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.trim().split("\\s+");
                // 获取进程ID
                if (parts.length > 0) {
                    String pid = parts[parts.length - 1];
                    System.out.println("Killing process with PID: " + pid);
                    killProcess(pid);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("=============【程序结束】=============");
    }

    /**
     * 根据pid杀死进程
     * @param pid
     */
    private static void killProcess(String pid) {
        String command = "cmd /c taskkill /F /PID " + pid;
        try {
            // 执行命令
            Process process = Runtime.getRuntime().exec(command);
            // 等待命令执行完成
            process.waitFor();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}